# -*- coding:utf-8 -*-

import requests
from lxml import etree
from fake_useragent import UserAgent
from http import cookiejar
import json
from datetime import datetime
import time
import re
import csv
import os
from pymongo import MongoClient

from utils.HttpUtils import HttpUtils

requests.packages.urllib3.disable_warnings()  # 忽略HTTPS安全警告

"""
108012  CQ92c_3668041
108013  RkOTj_3668041
"""


class TestRequest():
    def __init__(self):
        # 声明一个CookieJar对象实例来保存cookie
        # requests.utils.dict_from_cookiejar(html.cookies)  # 获取cookies转dict
        # res.cookies.get_dict()  # 获取cookies
        self.cookie = cookiejar.CookieJar()
        # self.ua = UserAgent(use_cache_server=False)  # 禁用服务器缓存
        # self.ua = UserAgent(verify_ssl=False)  #
        self.headers = {
            'Host': 'm.dzyxedu.com',
            'Connection': 'keep-alive',
            'Accept': 'application/json, text/javascript, */*; q=0.01',
            'X-Requested-With': 'XMLHttpRequest',
            'User-Agent': 'Mozilla/5.0 (Linux; Android 10; ANG-AN00 Build/HUAWEIANG-AN00; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/86.0.4240.99 XWEB/4297 MMWEBSDK/20220805 Mobile Safari/537.36 MMWEBID/9407 MicroMessenger/8.0.27.2220(0x28001B37) WeChat/arm64 Weixin NetType/WIFI Language/zh_CN ABI/arm64',
            'token': 'b45c6f3f-7b3c-454f-b816-e04b20d00e1a',
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'Origin': 'https://m.dzyxedu.com',
            'Sec-Fetch-Site': 'same-origin',
            'Sec-Fetch-Mode': 'cors',
            'Sec-Fetch-Dest': 'empty',
            'Referer': 'https://m.dzyxedu.com/m/index/testAnalysis.html?senId=108012&permit=CQ92c_3668041&name=%E5%8D%B71%E4%B8%93%E4%B8%9A%E5%AE%9E%E8%B7%B5%E8%83%BD%E5%8A%9B-%E5%86%85%E7%A7%91%E5%AD%A6%EF%BC%88%E4%B8%AD%E7%BA%A7%EF%BC%89%E5%BA%94%E8%AF%95%E6%8C%87%E5%AF%BC%E5%8F%8A%E5%8E%86%E5%B9%B4%E8%80%83%E7%82%B9%E4%B8%B2%E8%AE%B2',
            'Accept-Encoding': 'gzip, deflate',
            'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7',
            'Cookie': 'Hm_lvt_057320d4ecbd59fbbc1154220e3e23d6=1660548734; PHPSESSID=met61jtentir35g1lcunjf9j22; acw_tc=0bde431216617818299821405e00f2d8c9bb96b04dc3f56b0db60ce461aa81; Hm_lpvt_057320d4ecbd59fbbc1154220e3e23d6=1661781838; SERVERID=b7104ba1d7212fe2b90f3dbbd92da23f|1661781843|1661779465'
        }

    def get_TiType(self, session_id, permit):
        """
        获取题id
        :param cursor:
        :return:
        """
        postData = {
            'session_id': session_id,  # 108012
            'permit': permit,  # CQ92c_3668041,
            'item_id': 'catalog',
            'good_id': '',
        }
        url = f"https://m.dzyxedu.com/api/exam/getUserAnswerDetail"
        html = HttpUtils.do_request("POST", url, self.headers, postData)

        data_json = json.loads(html.text)

        kemu = data_json['data']['name']  # 科目
        for d_sections in data_json['data']['sections']:
            tixing = d_sections['name']
            for d_group in d_sections['group'][0]['items']:
                id = d_group['id']  # 题目id
                self.get_contents(session_id, permit, id, kemu, tixing)
                time.sleep(2)

    def get_contents(self, session_id, permit, id, kemu, tixing):
        postData = {
            'session_id': session_id,  # 108012,
            'permit': permit,  # CQ92c_3668041,
            'item_id': id,  # id   06c177fb-de26-8748-f4c9-aa16c6a70c78
        }
        url = f"https://m.dzyxedu.com/api/exam/getUserAnswerDetail"
        html = HttpUtils.do_request("POST", url, self.headers, postData)

        timu_data_json = json.loads(html.text)

        content_json = timu_data_json['data'][0]['content']
        # tigan = content_json['main_stem']  # 题干
        # 题干
        if (content_json.get('main_stem') == None):
            tigan = content_json['stem']

            data_dict = dict()
            data_dict['科目'] = kemu
            data_dict['题型'] = tixing
            data_dict['题干'] = tigan
            data_dict['问题'] = content_json['stem']  # 问题
            data_dict['解析'] = content_json['key']['analysis']  # 解析
            data_dict['答案'] = content_json['key']['key']  # 答案
            for x in content_json['options']:
                xm = x['id']
                data_dict['选项_' + xm] = x['description']

            # 保存数据
            HttpUtils.dict_to_csv(kemu, data_dict)
        else:
            tigan = content_json.get('main_stem')

            for d in content_json['items']:
                data_dict = dict()
                data_dict['科目'] = kemu
                data_dict['题型'] = tixing
                data_dict['题干'] = tigan
                data_dict['问题'] = d['content']['stem']  # 问题
                data_dict['解析'] = d['key']['analysis']  # 解析
                data_dict['答案'] = d['key']['key']  # 答案
                for x in d['content']['options']:
                    xm = x['id']
                    data_dict['选项_' + xm] = x['description']

                # 保存数据
                HttpUtils.dict_to_csv(kemu, data_dict)


if __name__ == '__main__':
    test = TestRequest()
    """
    108012  CQ92c_3668041
    108013  RkOTj_3668041
    108014  4enbs_3668041
    108015  P6KD8_3668041
    108016  RGBjM_3668041
    108017  kh6CP_3668041
    108018  FjfDw_3668041
    108019  qD598_3668041
    """

    test.get_TiType(108019, 'qD598_3668041')


